import keyboard
import win32gui
import win32con
import win32api
import win32gui_struct
import os
import sys
import winshell

# 全局字典，用于记录每个窗口的置顶状态
window_topmost_status = {}
# 记录自启动状态
is_startup_enabled = False

# 系统托盘图标消息
WM_TASKBAR = win32gui.RegisterWindowMessage("TaskbarCreated")


def get_current_focused_window():
    return win32gui.GetForegroundWindow()


def set_window_topmost(window_handle, make_topmost):
    if window_handle:
        try:
            z_order = win32con.HWND_TOPMOST if make_topmost else win32con.HWND_NOTOPMOST
            win32gui.SetWindowPos(window_handle, z_order, 0, 0, 0, 0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
        except Exception:
            pass


def on_hotkey_pressed():
    focused_window = get_current_focused_window()
    if focused_window in window_topmost_status:
        new_status = not window_topmost_status[focused_window]
    else:
        new_status = True
    window_topmost_status[focused_window] = new_status
    set_window_topmost(focused_window, new_status)


def add_to_startup():
    startup_folder = os.path.join(os.getenv('APPDATA'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')
    script_path = os.path.abspath(sys.argv[0])
    shortcut_path = os.path.join(startup_folder, 'WindowTopmost.lnk')
    try:
        with winshell.shortcut(shortcut_path) as shortcut:
            shortcut.path = script_path
            shortcut.description = 'Window Topmost Script'
        return True
    except Exception:
        return False


def remove_from_startup():
    startup_folder = os.path.join(os.getenv('APPDATA'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')
    shortcut_path = os.path.join(startup_folder, 'WindowTopmost.lnk')
    try:
        if os.path.exists(shortcut_path):
            os.remove(shortcut_path)
        return True
    except Exception:
        return False


def check_startup_status():
    startup_folder = os.path.join(os.getenv('APPDATA'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')
    shortcut_path = os.path.join(startup_folder, 'WindowTopmost.lnk')
    return os.path.exists(shortcut_path)


# 系统托盘回调函数
def WndProc(hWnd, msg, wParam, lParam):
    global is_startup_enabled
    if msg == WM_TASKBAR:
        add_icon(hWnd)
    elif msg == win32con.WM_DESTROY:
        del_icon(hWnd)
        win32gui.PostQuitMessage(0)
    elif msg == win32con.WM_USER + 20:
        if lParam == win32con.WM_LBUTTONUP:
            # 处理左键点击事件，这里可以添加你想要的逻辑
            pass
        elif lParam == win32con.WM_RBUTTONUP:
            # 处理右键点击事件，显示菜单
            x, y = win32gui.GetCursorPos()
            menu = win32gui.CreatePopupMenu()
            checked_flag = win32con.MF_CHECKED if is_startup_enabled else win32con.MF_UNCHECKED
            win32gui.AppendMenu(menu, win32con.MF_STRING | checked_flag, 1, "自启动")
            win32gui.AppendMenu(menu, win32con.MF_STRING, 2, "退出")
            win32gui.SetForegroundWindow(hWnd)
            command = win32gui.TrackPopupMenu(menu, win32con.TPM_RETURNCMD | win32con.TPM_NONOTIFY, x, y, 0, hWnd, None)
            win32gui.DestroyMenu(menu)
            if command == 1:
                is_startup_enabled = not is_startup_enabled
                if is_startup_enabled:
                    add_to_startup()
                else:
                    remove_from_startup()
            elif command == 2:
                # 点击退出选项，销毁窗口并退出程序
                win32gui.DestroyWindow(hWnd)
    return win32gui.DefWindowProc(hWnd, msg, wParam, lParam)


# 添加系统托盘图标
def add_icon(hWnd):
    # 加载打包时使用的图标
    try:
        hicon = win32gui.LoadImage(win32api.GetModuleHandle(None), 1, win32con.IMAGE_ICON, 0, 0,
                                   win32con.LR_SHARED)
    except Exception:
        hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
    flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
    nid = (hWnd, 0, flags, win32con.WM_USER + 20, hicon, '窗口置顶工具 ALT + D')
    win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid)


# 删除系统托盘图标
def del_icon(hWnd):
    nid = (hWnd, 0)
    win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, nid)


if __name__ == "__main__":
    is_startup_enabled = check_startup_status()
    try:
        keyboard.add_hotkey('alt+d', on_hotkey_pressed)
        # 创建窗口类
        wc = win32gui.WNDCLASS()
        hinst = wc.hInstance = win32api.GetModuleHandle(None)
        wc.lpszClassName = "PythonTaskbar"
        wc.lpfnWndProc = WndProc
        class_atom = win32gui.RegisterClass(wc)
        # 创建窗口
        hWnd = win32gui.CreateWindow(class_atom, "Python Taskbar", 0, 0, 0, 0, 0, 0, 0, hinst, None)
        # 添加图标
        add_icon(hWnd)
        # 消息循环
        win32gui.PumpMessages()
    except Exception:
        pass